<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset"
        >
            <el-form
                :model="queryForm"
                label-position="right"
                label-width="80px"
            >
                <el-row :gutter="24" style="height: 50px;"
                v-if="showDepartment">
                    <el-col :span="8" >
                        <el-form-item label="管理部门:">
                            <el-select
                                v-model="queryForm.projId"
                                style="width: 100%;"
                                @change="handleChangeProjId"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.project"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                 <el-row :gutter="24" style="height: 50px;" v-if="role != 2">
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('label.grade') + ':'"
                            :error="
                                queryForm.projId == '1' &&
                                !queryForm.grade &&
                                !!queryForm.departmentId
                                    ? $t('culture.rules.plsChooseGrade')
                                    : ''
                            "
                        >
                            <!-- <el-select
                                v-model="queryForm.grade"
                                style="width: 100%;"
                                clearable
                                @change="
                                    queryForm.projId == '1'
                                        ? queryCampusMajor
                                        : ''
                                "
                            >
                                <el-option
                                    v-for="item in options.grade"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select> -->
                            <el-date-picker
                                v-model="queryForm.grade"
                                type="year"
                                style="width:100%"
                                value-format="yyyy" 
                                :placeholder="$t('graduationList.pleaseSelect')">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.trainingLevel') + ':'">
                            <el-select
                                v-model="queryForm.trainingLevel"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.formLearning') + ':'">
                            <el-select
                                v-model="queryForm.formLearning"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.formLearning"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" style="height:51px">
                        <el-form-item :label="$t('label.college') + ':'">
                            <el-select
                                v-model="queryForm.departmentId"
                                @change="queryCampusMajor"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.college"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <template v-if="queryForm.projId == '1'">
                        <el-col :span="8">
                            <el-form-item
                                filterable
                                label="校内专业:"
                                prop="campusProfession"
                            >
                                <el-select
                                    v-model="queryForm.campusProfession"
                                    style="width: 100%"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options.campusProfessions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-else>
                        <el-col :span="8">
                            <el-form-item
                                filterable
                                :label="$t('label.major') + ':'"
                                prop="major"
                            >
                                <el-select
                                    v-model="queryForm.major"
                                    style="width: 100%"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options.major"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col :span="8">
                        <el-form-item label="在校状态:">
                            <el-select
                                v-model="queryForm.leaveSchool"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in options.schoolStatus"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('culturePlan.specialPlan') + ':'"
                        >
                            <el-select
                                v-model="queryForm.spcialPlan"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.spcialPlan"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('culturePlan.trainingCategory') + ':'"
                        >
                            <el-select
                                v-model="queryForm.trainingCategory"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.trainingCategory"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('culturePlan.degreeType') + ':'"
                        >
                            <el-select
                                v-model="queryForm.degreeType"
                                style="width: 100%;"
                                @change="queryCampusMajor"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.degreeType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="国际学生:">
                            <el-select v-model="queryForm.isStudentAbroad" style="width: 100%;">
                                <el-option v-for="item in options.international" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="8">
                        <el-form-item :label="$t('message.status') + ':'">
                            <el-select
                                v-model="queryForm.statusPlan"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.statusPlan"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否完成:">
                            <el-select
                                v-model="queryForm.plansComplete"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    key="0"
                                    label="未完成"
                                    value="0"
                                ></el-option>
                                <el-option
                                    key="1"
                                    label="已完成"
                                    value="1"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="导师:" prop="associationStatus">
                            <el-input
                                v-model="queryForm.teacherName"
                                placeholder="输入姓名/工号"
                            />
                        </el-form-item>
                    </el-col> 
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card
            v-loading="loading"
            shadow="never"
            body-style="padding: 24px;"
            class="card-margin"
        >
            <h1 class="condition-title">{{ $t("culturePlan.manage") }}</h1>
            <div class="div-main clearfix">
                <div class="float-left">
                    <el-input
                        v-model="queryForm.name"
                        :placeholder="$t('culturePlan.searchBySid')"
                        style="width:200px"
                        @keyup.enter.native="onSubmit"
                    >
                        <i
                            class="el-icon-search"
                            slot="suffix"
                            style="margin-top:10px;cursor:pointer"
                            @click="onSubmit"
                        ></i>
                    </el-input>
                </div>

                <div class="float-right" v-if="false">
                    <el-button @click="showBatchChangeDialog"
                        >批量修改</el-button
                    >
                    <el-button type="primary" @click="getStatistic"
                        >统计报表</el-button
                    >
                </div>
                <div class="float-right">
                    <el-button type="primary" @click="exportComplete"
                        >计划完成情况统计导出</el-button
                    >
                    <el-button type="primary" @click="refresh"
                        >刷新计划完成情况</el-button
                    >
                    <el-button type="primary" @click="pageExport"
                        >页面导出</el-button
                    >
                    <el-button type="primary" @click="exportPlanPdf"
                        >计划导出</el-button
                    >
                </div>
            </div>
            <el-table
                stripe
                :data="students"
                @selection-change="chooseStudent"
                style="width: 100%"
                tooltip-effect="light"
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column
                    prop="grade"
                    :label="$t('label.grade')"
                    width="80"
                ></el-table-column>
                <el-table-column
                    prop="studentId"
                    :label="$t('culturePlan.studentId')"
                    width="100"
                ></el-table-column>
                <el-table-column
                    prop="name"
                    :label="$t('culturePlan.name')"
                    width="80"
                ></el-table-column>
                <el-table-column :label="$t('label.trainingLevel')" width="80">
                    <template slot-scope="props">{{
                        props.row.trainingLevel
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('culturePlan.trainingCategory')"
                    width="90"
                >
                    <template slot-scope="props">{{
                        props.row.trainingCategory
                    }}</template>
                </el-table-column>
                <el-table-column :label="$t('culturePlan.degreeType')">
                    <template slot-scope="props">{{
                        props.row.degreeType
                    }}</template>
                </el-table-column>
                <el-table-column :label="$t('label.formLearning')">
                    <template slot-scope="props">{{
                        props.row.formLearning
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('label.college')"
                    min-width="200"
                    show-overflow-tooltip
                >
                    <template slot-scope="props">{{
                        props.row.departmentId
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('label.major')"
                    min-width="180"
                    show-overflow-tooltip
                >
                    <template slot-scope="props">{{
                        props.row.major
                    }}</template>
                </el-table-column>
                <el-table-column label="是否完成" width="80">
                    <template slot-scope="scope">
                        <span
                            v-if="scope.row.plansComplete == 0">
                            未完成
                        </span>
                        <span
                            v-if="scope.row.plansComplete == 1">
                            已完成
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="导师" prop="teacherName" width="80"/>
                <el-table-column :label="$t('message.status')" width="100">
                    <template slot-scope="scope">
                        <el-tag
                            v-if="scope.row.statusPlan == -1"
                            type="info"
                            size="mini"
                            disable-transitions
                            >未定义</el-tag
                        >
                        <el-tag
                            v-if="scope.row.statusPlan == 0"
                            type="info"
                            size="mini"
                            disable-transitions
                            >{{ $t("message.draft") }}</el-tag
                        >
                        <el-tag
                            v-if="scope.row.statusPlan == 1"
                            type="warning"
                            size="mini"
                            disable-transitions
                            >{{ $t("message.checking") }}</el-tag
                        >
                        <el-tag
                            v-if="scope.row.statusPlan == 2"
                            type="danger"
                            size="mini"
                            disable-transitions
                            >驳回</el-tag
                        >
                        <el-tag
                            v-if="scope.row.statusPlan == 3"
                            type="success"
                            size="mini"
                            disable-transitions
                            >{{ $t("message.pass") }}</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    v-if="!showOperateButton"
                    :label="$t('message.operating')"
                    width="100"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="customPlan(scope.row)"
                            size="mini"
                            >{{ $t("culturePlan.previewPlan") }}</el-button
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    v-if="showOperateButton"
                    :label="$t('message.operating')"
                    width="100"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <div
                            v-if="
                                scope.row.trainingLevel ||
                                    scope.row.trainingLevelCode
                            "
                        >
                            <el-button
                                type="text"
                                v-if="
                                    scope.row.passHistory == 0 &&
                                        (scope.row.statusPlan == -1 ||
                                            scope.row.statusPlan == 0)
                                "
                                @click="customPlan(scope.row)"
                                size="mini"
                                >{{ $t("culturePlan.customPlan") }}</el-button
                            >
                            <el-button
                                type="text"
                                v-if="
                                    scope.row.passHistory == 0 &&
                                        scope.row.statusPlan == 2
                                "
                                @click="customPlan(scope.row)"
                                size="mini"
                                >{{ $t("culturePlan.customPlan") }}</el-button
                            >

                            <el-button
                                type="text"
                                v-if="
                                    scope.row.passHistory == 1 &&
                                        scope.row.statusPlan != 1
                                "
                                @click="customPlan(scope.row)"
                                size="mini"
                                >{{ $t("culturePlan.previewPlan") }}</el-button
                            >

                            <el-button
                                type="text"
                                v-if="scope.row.statusPlan == 1"
                                @click="customPlan(scope.row)"
                                size="mini"
                                >{{ $t("culturePlan.previewPlan") }}</el-button
                            >
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20, 50, 100, 500, 1000]"
                        :page-size="queryForm.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="queryForm.total_"
                        style="float:right;margin-top:10px"
                    ></el-pagination>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            title="批量修改培养计划"
            :visible.sync="showChangeDialog"
            width="800px"
            @close="closeBatchForm()"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div>
                <el-radio v-model="radio" label="replace" @change="radioChange"
                    >批量替换</el-radio
                >
                <el-radio v-model="radio" label="add" @change="radioChange"
                    >批量新增</el-radio
                >
                <el-radio v-model="radio" label="delete" @change="radioChange"
                    >批量删除</el-radio
                >
            </div>
            <div v-if="radio == 'replace'" style="margin:20px">
                <el-form
                    :model="batchReplaceForm"
                    ref="batchReplaceForm"
                    label-position="left"
                    label-width="80px"
                    :rules="rules"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="原课程：" prop="oldCourseCode">
                                <el-select
                                    v-model="batchReplaceForm.oldCourseText"
                                    :remote-method="selectOldCourses"
                                    remote
                                    placeholder="请输入课程名称或编码"
                                    filterable
                                    style="width:200px;"
                                    @change="changeOldCourse"
                                >
                                    <el-option
                                        v-for="item in replaceOldCourses"
                                        :key="item.value"
                                        :label="item.value"
                                        :value="item.value"
                                        >({{ item.value }})&nbsp;{{
                                            item.label
                                        }}&nbsp;&nbsp;{{
                                            item.credits
                                        }}分</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="新课程：" prop="newCourseCode">
                                <el-select
                                    v-model="batchReplaceForm.newCourseText"
                                    :remote-method="selectNewCourses"
                                    remote
                                    placeholder="请输入课程名称或编码"
                                    filterable
                                    style="width:200px;"
                                    @change="changeNewCourse"
                                >
                                    <el-option
                                        v-for="item in replaceNewCourses"
                                        :key="item.value"
                                        :label="item.value"
                                        :value="item.value"
                                        >({{ item.value }})&nbsp;{{
                                            item.label
                                        }}&nbsp;&nbsp;{{
                                            item.credits
                                        }}分</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <i class="el-icon-info secondary-text" style
                                >新课程学分需要与旧课程相同</i
                            >
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div v-if="radio == 'add'" style="margin:20px">
                <el-form
                    :model="batchAddForm"
                    ref="batchAddForm"
                    label-position="left"
                    label-width="80px"
                    :rules="rules2"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="新增课程："
                                prop="addCourseCode"
                            >
                                <el-select
                                    v-model="batchAddForm.addCourseText"
                                    :remote-method="selectAddCourses"
                                    remote
                                    placeholder="请输入课程名称或编码"
                                    filterable
                                    style="width:200px;"
                                    @change="changeAddCourse"
                                >
                                    <el-option
                                        v-for="item in addCourses"
                                        :key="item.value"
                                        :label="item.value"
                                        :value="item.value"
                                        >({{ item.value }})&nbsp;{{
                                            item.label
                                        }}</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('label.trainingLevel')">
                                <el-select
                                    v-model="batchAddForm.trainingLevel"
                                    style="width: 200px;"
                                    @change="changeTrainingLevel"
                                >
                                    <el-option
                                        v-for="item in options.trainingLevel"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="课程类别："
                                prop="courseCategory"
                            >
                                <el-select
                                    v-model="batchAddForm.courseCategory"
                                    style="width: 200px;"
                                >
                                    <el-option
                                        v-for="item in courseLabels"
                                        :style="{
                                            textIndent: item.indent + 'px'
                                        }"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div v-if="radio == 'delete'" style="margin:20px">
                <el-form
                    :model="batchDeleteForm"
                    ref="batchDeleteForm"
                    label-position="left"
                    label-width="80px"
                    :rules="rules3"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="删除课程："
                                prop="deleteCourseCode"
                            >
                                <el-select
                                    v-model="batchDeleteForm.deleteCourseText"
                                    :remote-method="selectDeleteCourses"
                                    remote
                                    placeholder="请输入课程名称或编码"
                                    filterable
                                    style="width:200px;"
                                    @change="changeDeleteCourse"
                                >
                                    <el-option
                                        v-for="item in deleteCourses"
                                        :key="item.value"
                                        :label="item.value"
                                        :value="item.value"
                                        >({{ item.value }})&nbsp;{{
                                            item.label
                                        }}</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div style="text-align:right">
                <el-button @click="closeBatchForm">取消</el-button>
                <el-button type="primary" @click="batchConfirm">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog
            title="批量结果提示"
            :visible.sync="showResultDialog"
            width="800px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-row :gutter="20">
                <el-col>
                    <div style="font-size:18px">
                        <i class="el-icon-warning"></i>
                        本次批量修改培养计划{{
                            result.totalNumber
                        }}个，修改成功{{ result.successNumber }}个，修改失败{{
                            result.failNumber
                        }}个。
                    </div>
                </el-col>
            </el-row>
            <div v-if="result.failNumber">
                <el-button type="text" @click="download" size="mini"
                    >点此导出excel查看详情</el-button
                >
            </div>
            <div style="text-align:right">
                <el-button type="primary" @click="closeResultDialog"
                    >确定</el-button
                >
            </div>
        </el-dialog>
    </div>
</template>
<script>
import bus from "common/src/utils/bus";
import { findProfessionByParam } from "common/src/api/culture/cultruescheme";
import { getGraduateDegreePage } from "common/src/api/resource/course";
import { getPower } from "common/src/api/culture/culturePlan";
import {
    queryDic,
    findTrainingLevelByProjId,
    sortTrainingCategories
} from "common/src/api/dictionary";
import { findFaculty } from "common/src/api/faculty";
import {
    findStudentCultureRelList,
    batchDelete,
    batchReplace,
    batchAdd,
    batchResult,
    exportPlanPdfList,
    exportPage,
    updatePlansCompleteStatistical,
    exportPlansCompleteStatistical
} from "common/src/api/culture/culturePlan";
import { getCourseList, getCourseAllList } from "common/src/api/courseTemplate";
import UTILS from "common/src/utils/utils";
import mixin from 'common/src/mixins/index';
export default {
    name: "personalPlanManage",
    mixins: [mixin],
    data() {
        return {
            queryForm: {
                grade: "", //年级
                trainingLevel: "", //培养层次
                degreeType: "", //学位类型
                departmentId: "", //学院
                major: "", //专业
                campusProfession: "", //校内专业
                formLearning: "", //学习形式
                spcialPlan: "", //专项计划
                trainingCategory: "", //培养类别
                isStudentAbroad: "", //国际学生
                statusPlan: "", //状态
                plansComplete:"",
                studentId: "", //学号
                associationStatus: "1", //已绑定培养方案
                projId: "",
                pageSize_: 20,
                pageNum_: 1,
                total_: 0,
                teacherName:"",
                leaveSchool: "" //在校状态
            },
            options: {
                grade: [], //年级
                trainingLevel: [], //培养层次
                formLearning: [], //学习形式
                degreeType: [], //学位类型
                spcialPlan: [], //专项计划
                college: [], //学院
                major: [], //专业
                campusProfessions: [], //校内专业
                trainingCategory: [], //培养类别
                international: [], //国际学生
                statusPlan: [], //状态
                project: [],
                schoolStatus: [] //在校状态
            },
            //当前页学生id集合
            studentIds: [],
            //按钮位置
            btnParams: "",
            students: [],
            chooseStudents: [],
            //批量弹框属性
            showChangeDialog: false,
            showResultDialog: false,
            result: {
                totalNumber: "",
                successNumber: "",
                failNumber: "",
                path: ""
            },
            role: "",
            radio: "replace",
            batchReplaceForm: {
                oldCourseCode: "",
                oldCourseText: "",
                newCourseCode: "",
                newCourseText: "",
                oldCredits: 0,
                newCredits: 0
            },
            batchDeleteForm: {
                deleteCourseText: "",
                deleteCourseCode: ""
            },
            batchAddForm: {
                addCourseText: "",
                addCourseCode: "",
                courseCategory: "",
                trainingLevel: ""
            },
            replaceOldCourses: [],
            replaceNewCourses: [],
            deleteCourses: [],
            addCourses: [],
            courseLabels: [],
            rules: {
                oldCourseCode: [
                    {
                        required: true,
                        message: "必须填写课程编码",
                        trigger: "blur"
                    }
                ],
                newCourseCode: [
                    {
                        required: true,
                        message: "必须填写课程编码",
                        trigger: "blur"
                    }
                ]
            },
            rules2: {
                addCourseCode: [
                    {
                        required: true,
                        message: "必须填写课程编码",
                        trigger: "blur"
                    }
                ],
                courseCategory: [
                    {
                        required: true,
                        message: "必须选择课程分类",
                        trigger: "blur"
                    }
                ]
            },
            rules3: {
                deleteCourseCode: [
                    {
                        required: true,
                        message: "必须填写课程编码",
                        trigger: "blur"
                    }
                ]
            },
            loadConfig: {
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(255, 255, 255, .48)"
            },
            showDepartment: false
        };
    },
    mounted() {
        this.init();
        this.getRole();
        this.setOperateButtonVisible();
        this.initProjId();
        // bus.$on("updateCurrentManageDeptId", id => {
        //     this.queryForm.projId = id;
        //     this.handleChangeProjId();
        // });
    },
    methods: {
        // initProjId() {
        //     let currentUser =
        //         (this.$store.state.session && this.$store.state.session.user) ||
        //         JSON.parse(localStorage.getItem("user"));
        //     if (currentUser.currentRole == 1) {
        //         this.queryForm.projId = currentUser.currentManageDptId;
        //         this.handleChangeProjId();
        //     } else {
        //         this.initProjs();
        //     }
        // },
        initProjId() {
            let currentUser =this.global.currentUser;
            if(currentUser.currentRole == 1 ) {
                 this.queryForm.projId = currentUser.currentManageDptId;
                //this.queryForm.projId = '2';
                this.handleChangeProjId();
            } else {
                this.initProjs();
            }
            this.currentRole = currentUser.currentRole;
        },
        getRole() {
            getPower().then(res => {
                this.role = res.data.power;
                if(!this.global.isAnyTeacher){
                    if (res.data.departmentCode.indexOf(",") != -1) {
                        let departmentCode = res.data.departmentCode.split(",");
                        this.queryForm.departmentId = departmentCode[0];
                    } else {
                        this.queryForm.departmentId = res.data.departmentCode;
                    }
                    if (res.data.departmentCode && res.data.power == 3) {
                        this.queryCampusMajor();
                    }
                    if (this.queryForm.departmentId) {
                        this.onSubmit();
                    }
                }
            });
        },
        setOperateButtonVisible() {
            let currentUser =
                this.$store.state.session.user ||
                JSON.parse(localStorage.getItem("user"));
            this.showOperateButton = currentUser.currentRole == 1;
        },
        initCurrentRole() {
            let currentUser =this.global.currentUser;
            this.showDepartment = currentUser.currentRole == "2"&&this.options.project.length>1;
            this.isManage = currentUser.currentRole == 1;
        },
        init() {
            //绑定年级
            let now = new Date();
            let currentYear = now.getFullYear() + 1,
                minYear = currentYear - 11;
            for (let grade = currentYear; grade > minYear; grade--) {
                let obj = { label: grade, value: grade };
                this.options.grade.push(obj);
            }
            //状态
            this.options.statusPlan.push({
                label: '未定义',
                value: -1
            });
            this.options.statusPlan.push({
                label: this.$t("message.draft"),
                value: 0
            });
            this.options.statusPlan.push({
                label: this.$t("message.checking"),
                value: 1
            });
            this.options.statusPlan.push({
                label: this.$t("message.refuse"),
                value: 2
            });
            this.options.statusPlan.push({
                label: this.$t("message.pass"),
                value: 3
            });
            findFaculty().then(res => {
                let data = { X_YX: res.data };
                UTILS.fillSelect({ college: "X_YX" }, data, this.options);
            });
            //筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "X_PYCC",
                    "K_XXXS",
                    "X_ZXJH",
                    "X_PYLB",
                    "X_XWLX",
                    "isAborad",
                    "X_LXZT"
                ]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    let params = {
                        lang: this.$store.getters.language,
                        keys: ["X_PYLB"]
                    };
                    sortTrainingCategories(params).then(res => {
                        this.options.trainingCategory = res.data.X_PYLB;
                    });
                    UTILS.fillSelect(
                        {
                            trainingLevel: "X_PYCC",
                            spcialPlan: "X_ZXJH",
                            formLearning: "K_XXXS",
                            degreeType: "X_XWLX",
                            // trainingCategory: "X_PYLB",
                            international: "isAborad",
                            schoolStatus: "X_LXZT"
                        },
                        res.data,
                        this.options
                    );
                }
            });
        },
        async initProjs() {
            // let params = {
            //     lang: this.$store.getters.language || "cn",
            //     type: "allChild",
            //     keys: ["X_GLBM"]
            // };
            // let res = await queryDic(params);
            // let user =
            //     this.$store.state.session.user ||
            //     JSON.parse(localStorage.getItem("user"));
            // let { manageDptIds } = user;
            // let {
            //     code,
            //     data: { X_GLBM }
            // } = res;
            // if (code === 200) {
            //     let dpts = Object.keys(X_GLBM).map(item => ({
            //         label: X_GLBM[item],
            //         value: item + ""
            //     }));
            //     this.options.projIds =
            //         manageDptIds &&
            //         manageDptIds instanceof Array &&
            //         manageDptIds.length > 0
            //             ? dpts.filter(item => {
            //                   return manageDptIds.indexOf(item.value) > -1;
            //               })
            //             : [];
            //     this.queryForm.projId = this.options.projIds[0].value;
            //     this.handleChangeProjId();
            // }
            let params = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_GLBM"]
            };
            let res = await queryDic(params);
            let {code, data: {X_GLBM}} = res;
            if (code === 200) {
                let dpts = Object.keys(X_GLBM).map(item => ({
                    label: X_GLBM[item],
                    value: item + ""
                }))
                this.options.project = dpts.filter(item => {
                    return item.value != 1;
                }) 
            }
            console.log(this.options.project)
            this.queryForm.projId = this.options.project[0].value;
            //this.queryForm.projId = "2";
            this.initCurrentRole();
            this.handleChangeProjId()
        },
        handleChangeProjId() {
            this.changeTrainingLevelOptions();
            this.onSubmit();
        },
        changeTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.queryForm.trainingLevel = "";
            this.options.optionKey = [];
            _.each(dataObj, level => {
                this.options.optionKey.push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        onSubmit() {
            this.getStudentList();
            this.studentIds = [];
        },
        getStudentList(isFirstPage = true) {
            if (isFirstPage) {
                this.queryForm.pageNum_ = 1;
            }
            findStudentCultureRelList(this.queryForm).then(response => {
                if (response.code == 200) {
                    this.students = response.data.list;
                    for (var i = 0; i < response.data.list.length; i++) {
                        this.studentIds.push(response.data.list[i].studentId);
                    }

                    this.queryForm.total_ = response.data.total_;
                }
            });
        },
        reset() {
            this.queryForm.grade = "";
            this.queryForm.trainingLevel = "";
            this.queryForm.major = "";
            this.queryForm.campusProfession = "";
            this.queryForm.trainingCategory = "";
            this.queryForm.degreeType = "";
            this.queryForm.formLearning = "";
            this.queryForm.isStudentAbroad = "";
            this.queryForm.spcialPlan = "";
            this.queryForm.studentId = "";
            this.queryForm.statusPlan = "";
            this.queryForm.leaveSchool = "1";
            this.queryForm.teacherName = "";
            this.queryForm.plansComplete = "";
            this.queryForm.leaveSchool = ""
            if (this.role != 3) {
                this.queryForm.departmentId = "";
                this.options.campusProfessions = [];
                this.options["major"] = [];
            }
            this.onSubmit();
        },
        //选择复选框
        chooseStudent(val) {
            this.chooseStudents = val;
        },
        queryCampusMajor() {
            this.queryForm.major = "";
            this.queryForm.campusProfession = "";
            if (this.queryForm.projId == "1") {
                this.queryCampusProfessions();
            } else this.queryMajors();
        },
        queryCampusProfessions() {
            this.options.campusProfessions = [];
            // 联动校验
            if (!(this.queryForm.grade && this.queryForm.departmentId)) {
                return;
            }
            const query = {};
            query.category = this.queryForm.professionCateGory;
            query.faculty = this.queryForm.departmentId;
            query.grade = this.queryForm.grade;
            query.trainingLevel = this.queryForm.trainingLevel;
            findProfessionByParam(query).then(res => {
                if (res.code == 200) {
                    this.options.campusProfessions = res.data.map(
                        (item, index) => {
                            return {
                                label: item.professionCateGoryName,
                                value: item.professionCateGory
                            };
                        }
                    );
                }
            });
        },
        queryMajors() {
            // if (this.queryForm.departmentId) {
            this.options["major"] = [];
            const data = {
                college: this.queryForm.departmentId,
                type: this.queryForm.degreeType,
                page: false
            };
            getGraduateDegreePage(data).then(res => {
                if (res.code === 200) {
                    this.options["major"] = [];
                    let majors = _.map(res.data.list, item => {
                        return {
                            value: item.code,
                            label:
                            "cn" === this.$store.getters.language
                                ? item.name + ' ' + item.code
                                : item.nameEn + ' ' + item.code
                        };
                    });
                    majors &&
                        0 < majors.length &&
                        (this.options["major"] = [...majors]);
                }
            });
            // }
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getStudentList();
        },
        handleCurrentChange(val) {
            this.studentIds = [];
            this.queryForm.pageNum_ = val;
            this.getStudentList(false);
        },
        customPlan(row) {
            if (row.trainingLevelCode) {
                this.$router.push({
                    path: `/personalPlanDetail/${row.studentId}`,
                    query: {
                        templateId: row.templateId
                    }
                });
            }
        },
        //批量修改
        showBatchChangeDialog() {
            this.radio = "replace";
            this.showChangeDialog = true;
            this.resetFields();
        },
        //统计查看
        getStatistic() {
            //TODO:
        },
        exportPlanPdf() {
            if (this.chooseStudents.length == 0) {
                this.$message({
                    type: "info",
                    message: "请选择要导出的学生"
                });
                return;
            }

            let params = {
                ids: this.chooseStudents.map(c => c.studentId),
                "x-token":
                    this.$store.state.session.sessionid ||
                    localStorage.getItem("sessionid") ||
                    ""
            };
            console.log(params);
            let url = exportPlanPdfList(params);
            window.open(url);
        },
        //批量提交
        batchConfirm() {
            if (this.radio == "replace") {
                //替换
                this.$refs.batchReplaceForm.validate(valid => {
                    if (!valid) {
                        return;
                    }
                    if (
                        this.batchReplaceForm.oldCredits !=
                        this.batchReplaceForm.newCredits
                    ) {
                        this.$message({
                            type: "info",
                            message: "原课程学分必须与新课程学分一致"
                        });
                        return;
                    }
                    if (
                        this.batchReplaceForm.oldCourseCode ==
                        this.batchReplaceForm.newCourseCode
                    ) {
                        this.$message({
                            type: "info",
                            message: "原课程与新课程不能相同"
                        });
                        return;
                    }
                    this.handleBatchReplace();
                });
            } else if (this.radio == "add") {
                //添加
                this.$refs.batchAddForm.validate(valid => {
                    if (!valid) {
                        return;
                    }
                    this.handleBatchAdd();
                });
            } else {
                //删除
                this.$refs.batchDeleteForm.validate(valid => {
                    if (!valid) {
                        return;
                    }
                    this.handleBatchDelete();
                });
            }
        },
        //处理批量替换
        handleBatchReplace() {
            let loading = this.$loading(this.loadConfig);
            let data = _.cloneDeep(this.queryForm);
            data.statusPlan = 4;
            data.studentIds = [];
            (data.newCourseCode = this.batchReplaceForm.newCourseCode),
                (data.oldCourseCode = this.batchReplaceForm.oldCourseCode),
                batchReplace(data)
                    .then(res => {
                        if (res.code == 200) {
                            this.delayRequest(res.data.key, loading);
                        } else {
                            loading.close();
                        }
                    })
                    .catch(ex => {
                        this.$message({
                            type: "error",
                            message: ex
                        });
                        loading.close();
                    });
        },
        //处理批量添加
        handleBatchAdd() {
            let loading = this.$loading(this.loadConfig);
            let data = _.cloneDeep(this.queryForm);
            data.statusPlan = 4;
            data.studentIds = [];
            data.newCourseCode = this.batchAddForm.addCourseCode;
            data.labelId = this.batchAddForm.courseCategory;
            batchAdd(data)
                .then(res => {
                    if (res.code == 200) {
                        this.delayRequest(res.data.key, loading);
                    } else {
                        loading.close();
                    }
                })
                .catch(ex => {
                    this.$message({
                        type: "error",
                        message: ex
                    });
                    loading.close();
                });
        },
        //处理批量删除
        handleBatchDelete() {
            let loading = this.$loading(this.loadConfig);
            let data = _.cloneDeep(this.queryForm);
            data.statusPlan = 4;
            data.studentIds = [];
            data.oldCourseCode = this.batchDeleteForm.deleteCourseCode;
            batchDelete(data)
                .then(res => {
                    if (res.code == 200) {
                        this.delayRequest(res.data.key, loading);
                    } else {
                        loading.close();
                    }
                })
                .catch(ex => {
                    this.$message({
                        type: "error",
                        message: ex
                    });
                    loading.close();
                });
        },
        //异步获取批量结果
        async delayRequest(key, loading) {
            await new Promise(resolve => setTimeout(resolve, 5000));
            batchResult(key)
                .then(res => {
                    if (res.code == 200 && res.data.status) {
                        this.showResultDialog = true;
                        this.result.totalNumber = res.data.must;
                        this.result.successNumber = res.data.success;
                        this.result.failNumber = res.data.fail;
                        this.result.path = res.data.path;
                        loading.close();
                    } else {
                        this.delayRequest(key, loading);
                    }
                })
                .catch(ex => {
                    this.delayRequest(key, loading);
                });
        },
        closeBatchForm() {
            this.showChangeDialog = false;
            this.resetFields();
        },
        //批量类型改变
        radioChange() {
            this.resetFields();
        },
        //清空Form字段
        resetFields() {
            if (this.$refs.batchReplaceForm)
                this.$refs.batchReplaceForm.resetFields();
            if (this.$refs.batchAddForm) this.$refs.batchAddForm.resetFields();
            if (this.$refs.batchDeleteForm)
                this.$refs.batchDeleteForm.resetFields();

            this.batchReplaceForm.oldCourseCode = "";
            this.batchReplaceForm.oldCourseText = "";
            this.batchReplaceForm.newCourseCode = "";
            this.batchReplaceForm.newCourseText = "";
            this.batchAddForm.addCourseText = "";
            this.batchAddForm.addCourseCode = "";
            this.batchAddForm.trainingLevel = "";
            this.batchAddForm.courseCategory = "";
            this.courseLabels.length = 0;
            this.batchDeleteForm.deleteCourseText = "";
            this.batchDeleteForm.deleteCourseCode = "";
        },
        //查询删除课程
        selectDeleteCourses(query) {
            this.remoteQuery(this.deleteCourses, query);
        },
        //查询替换旧课程
        selectOldCourses(query) {
            this.remoteQuery(this.replaceOldCourses, query);
        },
        //查询替换新课程
        selectNewCourses(query) {
            this.remoteQuery(this.replaceNewCourses, query);
        },
        //查询新增课程
        selectAddCourses(query) {
            this.remoteQuery(this.addCourses, query);
        },
        //选中删除的课程
        changeDeleteCourse(val) {
            let course = this.deleteCourses.find(c => c.value == val);
            this.batchDeleteForm.deleteCourseText =
                course.label + "(" + val + ")";
            this.batchDeleteForm.deleteCourseCode = course.id;
        },
        //选中替换旧的课程
        changeOldCourse(val) {
            let course = this.replaceOldCourses.find(c => c.value == val);
            this.batchReplaceForm.oldCourseText =
                course.label + "(" + val + ") (" + course.credits + "分)";
            this.batchReplaceForm.oldCourseCode = course.id;
            this.batchReplaceForm.oldCredits = course.credits;
        },
        //选中替换新的课程
        changeNewCourse(val) {
            let course = this.replaceNewCourses.find(c => c.value == val);
            this.batchReplaceForm.newCourseText =
                course.label + "(" + val + ") (" + course.credits + "分)";
            this.batchReplaceForm.newCourseCode = course.id;
            this.batchReplaceForm.newCredits = course.credits;
        },
        //选中新增的课程
        changeAddCourse(val) {
            let course = this.addCourses.find(c => c.value == val);
            this.batchAddForm.addCourseText = course.label + "(" + val + ")";
            this.batchAddForm.addCourseCode = course.id;
        },
        //远程查询
        remoteQuery(array, query) {
            array.length = 0;
            getCourseList({
                trainingLevel: "",
                formLearning: "",
                studentAbroad: "",
                condition: query,
                isElective: "",
                pageSize_: 20,
                pageNum_: 1,
                total_: 0
            }).then(res => {
                if (res.code == 200) {
                    for (var i = 0; i < res.data.list.length; i++) {
                        array.push({
                            label: res.data.list[i].name,
                            value: res.data.list[i].code,
                            id: res.data.list[i].id,
                            credits: res.data.list[i].credits
                        });
                    }
                }
            });
        },
        //改变培养层次
        changeTrainingLevel(val) {
            getCourseAllList({ trainingLevel: val }).then(res => {
                if (res.code == 200) {
                    let courseLabels = [];
                    this.loadCategoryRelation(courseLabels, res.data);
                    this.courseLabels = courseLabels;
                }
            });
        },
        //递归获取课程分类
        loadCategoryRelation(
            array = [],
            dataSource,
            parentId = 0,
            indent = 0,
            level = 1
        ) {
            dataSource.forEach(p => {
                if (p.parentId === parentId) {
                    array.push({
                        label: p.label,
                        value: p.id,
                        indent: indent,
                        level: level,
                        trainingLevel: p.trainingLevel,
                        isElective: p.isElective
                    });
                    this.loadCategoryRelation(
                        array,
                        dataSource,
                        p.id,
                        indent + 20,
                        level + 1
                    );
                }
            });
        },
        //下载失败xls
        download() {
            window.open(
                "/api/cultureservice/studentCultureRel/export?path=" +
                    this.result.path
            );
        },
        closeResultDialog() {
            this.showResultDialog = false;
        },
        pageExport() {
            let ids = this.chooseStudents.map(item => item.studentId);
            let params = _.cloneDeep(this.queryForm);
            exportPage(
                Object.assign(params, {
                    ids: ids + ""
                })
            );
        },
        refresh(){
            if(!this.queryForm.grade){
                this.$message({
                    type: "warning",
                    message: "请先选择需要刷新的年级"
                });
                return;
            }
            updatePlansCompleteStatistical({ projId: this.queryForm.projId,grade: this.queryForm.grade}).then(res => {
                if (res.code == 200) {
                    this.getStudentList();
                }
            });
        },
        exportComplete(){
            if(this.chooseStudents.length == 0){
                if(!this.queryForm.grade){
                    this.$message({
                        type: "warning",
                        message: "请先选择需要导出的年级"
                    });
                    return;
                }
            }
            let ids = this.chooseStudents.map(item => item.studentId);
            let params = _.cloneDeep(this.queryForm);
            exportPlansCompleteStatistical(
                Object.assign(params, {
                    ids: ids + ""
                })
            ); 
        }
    }
};
</script>

<style scoped>
.div-main {
    margin-bottom: 16px;
}
</style>
